/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.cef.entity.changeset;

import com.inspur.edp.cef.entity.entity.IEntityData;
import com.inspur.edp.cef.entity.entity.IEntityDataCollection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Objects;

public class DeletedChildChangeCollection implements Iterable<IChangeDetail> {

  private final IEntityData data;
  private DeleteChangeDetail change;
  private String childCode;

  public DeletedChildChangeCollection(
      DeleteChangeDetail change, IEntityData data, String childCode) {
    Objects.requireNonNull(change, "change");
    Objects.requireNonNull(data, "data");
    Objects.requireNonNull(childCode, "childCode");

    this.change = change;
    this.data = data;
    this.childCode = childCode;
  }

  public Iterator<IChangeDetail> iterator() {
    HashMap<String, IEntityDataCollection> childs = data.getChilds();
    if (childs.containsKey(childCode) == false) {
      return new Iterator<IChangeDetail>() {
        @Override
        public boolean hasNext() {
          return false;
        }

        @Override
        public IChangeDetail next() {
          return null;
        }
      };
    } else {
      return new Enumerator(childs.get(childCode)).iterator();
    }
  }

  private class Enumerator implements Iterable<IChangeDetail> {
    public IChangeDetail getCurrent() {
      return dataCollection != null
          ? (IChangeDetail) new DeleteChangeDetail(dataCollection.next().getID())
          : null;
    }

    private java.util.Iterator<IEntityData> dataCollection;

    public Enumerator(IEntityDataCollection addChange) {
      dataCollection = addChange.iterator();
    }

    public Iterator<IChangeDetail> iterator() {
      return new Iterator<IChangeDetail>() {
        @Override
        public boolean hasNext() {
          return dataCollection.hasNext();
        }

        @Override
        public IChangeDetail next() {
          return new DeleteChangeDetail(dataCollection.next().getID());
        }
      };
    }
  }
}
